//
//  WNReadVC+Func.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/19.
//

import UIKit

extension WNReadVC {
    /// 创建/替换控制器
    func creatPageVC(_ displayVC: WNCurrentReadVC? = nil) {
        clearVC()
        let flipStr = getReadConfigItem("flip") as? String ?? "Page"
        if flipStr == "Scroll" {
            scrollVC = WNReadScrollVC()
            scrollVC?.mainVC = self
            scrollVC?.view.frame = readView.bounds
            scrollVC?.view.backgroundColor  = isDark() ? .init(named: "black_121212") : .wn_colorWithHexString("\(getReadConfigItem("bgColor"))")
            readView.insertSubview(scrollVC!.view, at: 0)
            scrollVC?.readTabView.isScrollEnabled = !showTopBom
            addChild(scrollVC!)
        }else if flipStr == "Cover" {
            guard displayVC != nil else { return }
            coverVC = SNCoverVC()
            coverVC?.delegate = self
            coverVC?.view.frame = readView.bounds
            coverVC?.view.backgroundColor  = isDark() ? .init(named: "black_121212") : .wn_colorWithHexString("\(getReadConfigItem("bgColor"))")
            readView.insertSubview(coverVC!.view, at: 0)
            coverVC?.setController(displayVC)
        }else {
            guard displayVC != nil else { return }
            pageVC = UIPageViewController(transitionStyle: flipStr == "Page" ? .pageCurl : .scroll, navigationOrientation: .horizontal)
            pageVC?.delegate = self
            pageVC?.dataSource = self
            pageVC?.isDoubleSided = true
            pageVC?.view.frame = readView.bounds
            pageVC?.view.backgroundColor  = isDark() ? .init(named: "black_121212") : .wn_colorWithHexString("\(getReadConfigItem("bgColor"))")
            readView.insertSubview(pageVC!.view, at: 0)
            pageVC?.setViewControllers([displayVC!], direction: .forward, animated: true)
            pageVC?.isPagingEnabled = !showTopBom
        }
        currentReadVC = displayVC
    }
    
    /// 移除控制器
    func clearVC() {
        currentReadVC?.view.removeFromSuperview()
        currentReadVC?.removeFromParent()
        currentReadVC = nil
        if pageVC != nil {
            pageVC?.view.removeFromSuperview()
            pageVC?.removeFromParent()
            pageVC = nil
        }
        if coverVC != nil {
            coverVC?.view.removeFromSuperview()
            coverVC?.removeFromParent()
            coverVC = nil
        }
        if scrollVC != nil {
            scrollVC?.view.removeFromSuperview()
            scrollVC?.removeFromParent()
            scrollVC = nil
        }
    }
    
    /// 获取指定阅读记录阅读页
    func getReadVC(_ recModel: BookRecordModel?) -> WNCurrentReadVC? {
        guard let m = recModel else { return nil }
        if m.page.intValue == (m.chapterModel?.pageCount.intValue ?? 0)-1 {
            chapterReadComplete(m.chapterModel?.chapterId.intValue ?? 0, m.chapterModel?.chapterName ?? "")
            if m.chapterModel?.chapterNextId.intValue == -1 {
                chapterReadComplete()
            }
        }
        let vc = WNCurrentReadVC()
        vc.recordModel = m
        return vc
    }
    
    /// 获取仿真模式背面(只用于仿真模式背面显示)
    func getCurrentReadBackVC(_ recModel: BookRecordModel?) -> WNCurrentReadBackVC? {
        let vc = WNCurrentReadBackVC()
        vc.recordModel = recModel
        vc.view.addSubview(getReadVC(recModel)?.view ?? UIView())
        return vc
    }
    
    /// 获取当前阅读记录阅读页
    func getCurrentReadVC(_ isUpdateFont: Bool = false) -> WNCurrentReadVC? {
        if getReadConfigItem("flip") as? String == "Scroll" {
            return nil
        }
        if isUpdateFont {
            recordModel?.updateFont()
        }
        return getReadVC(recordModel)
    }
    
    /// 获取当前记录上一页阅读记录
    func getBeforeRead(_ recModel: BookRecordModel?) -> BookRecordModel? {
        guard let m = recModel, m.chapterModel != nil else { return nil }
        let rm = m
        let bookId = rm.bookId
        let chapterId = rm.chapterModel?.chapterPrevId ?? NSNumber(-1)
        if rm.chapterModel?.chapterPrevId.intValue == -1 && rm.page.intValue == 0 {
            return nil
        }
        isSelPage = false
        isPrevious = true
        if rm.page == 0 {
            if SNKeyedArchiver.isExist(bookId, chapterId.stringValue) {
                rm.modify(chapterId: chapterId, toPage: -1)
                chapterReadRequest()
            }else {
                handleChooseChapter(chapterId)
            }
        }else {
            rm.previousPage()
        }
        return rm
    }
    
    /// 获取当前记录下一页阅读记录
    func getAfterRead(_ recModel: BookRecordModel?) -> BookRecordModel? {
        guard let m = recModel, m.chapterModel != nil else { return nil }
        let rm = m
        let bookId = rm.bookId
        let chapterId = rm.chapterModel?.chapterNextId ?? NSNumber(-1)
        if rm.chapterModel?.chapterNextId.intValue == -1 && rm.page.intValue == (rm.chapterModel?.pageCount.intValue ?? 0)-1 {
            return nil
        }
        isSelPage = false
        isPrevious = false
        if rm.page.intValue == (rm.chapterModel?.pageCount.intValue ?? 0)-1 {
            if chapterArr.first(where: {$0.chapterId == chapterId}) == nil {
                return nil
            }
            if SNKeyedArchiver.isExist(bookId, chapterId.stringValue) {
                rm.modify(chapterId: chapterId, toPage: 0)
                chapterReadRequest()
            }else {
                handleChooseChapter(chapterId)
            }
        }else {
            rm.nextPage()
        }
        return rm
    }
    
    /// 处理跳转章节
    func handleChooseChapter(_ chapterId: NSNumber, _ autoLocked: Bool = true) {
        let chapter = chapterArr.first(where: {$0.chapterId == chapterId})
        if chapter == nil {
            return
        }
        if chapter?.status == 2 {
            if getAutoOpen() {
                if bookDetailModel?.feeType == 1 {
                    readLockView.isHidden = false
                    readLockView.chapterModel = chapter
                    navView.titleName = chapter?.chapterName
                }else {
                    if WNSingleData.shared.userGold >= (chapter?.price ?? 0) {
                        buyChapter(bookDetailModel?.bookId ?? "", chapter?.chapterId ?? 0, chapter?.price ?? 0, true)
                    }else {
                        getLockedChapterContent(chapterId, chapter)
                    }
                }
            }else {
                if autoLocked {
                    saveAutoOpen(true)
                }
                getLockedChapterContent(chapterId, chapter)
            }
        }else {
            selChapterId = chapterId
            goToChapter(selChapterId)
            readLockView.isHidden = true
        }
    }
    
    /// 跳转指定 章节&页码
    func goToChapter(_ chapterId: NSNumber, _ page: NSNumber = NSNumber(value: 0)) {
        WNBuriedManager.shared.choseChapterStart(recordModel?.bookId ?? "", chapterId.stringValue)
        if SNKeyedArchiver.isExist(recordModel?.bookId, chapterId.stringValue) {
            recordModel?.modify(chapterId: chapterId, toPage: page.intValue)
            handleChapterContent(recordModel?.chapterModel)
        }else {
            chapterContentRequest()
        }
    }
    
    /// 更新阅读记录
    func updateRead(_ recModel: BookRecordModel?) {
        if let rm = recModel {
            navView.titleName = rm.chapterModel?.chapterName
            recordModel = rm
            READ_RECORD_CURRENT_CHAPTER_LOCATION = rm.locationFirst?.intValue ?? 0
            recordModel?.updateFont()
        }
    }
}

extension WNReadVC {
    
    /// 处理章节内容
    func handleChapterContent(_ cdModel: ChapterDetailModel?, _ isLocal: Bool = true) {
        recordModel?.chapterModel = cdModel
        if isSelPage {
            READ_RECORD_CURRENT_CHAPTER_LOCATION = 0
        }else {
            if !isLocal && isPrevious {
                recordModel?.chapterModel?.updateFont()
                recordModel?.modify(model: recordModel?.chapterModel, toPage: (recordModel?.chapterModel?.pageCount.intValue ?? 1)-1)
                READ_RECORD_CURRENT_CHAPTER_LOCATION = recordModel?.chapterModel?.getLocationFirst(page: (recordModel?.chapterModel?.pageCount.intValue ?? 1)-1).intValue ?? 0
            }else {
                if scrollVC != nil {
                    if scrollVC!.isScrollUp {
                        READ_RECORD_CURRENT_CHAPTER_LOCATION = cdModel?.location.intValue ?? 0
                    }else {
                        recordModel?.chapterModel?.updateFont()
                        recordModel?.modify(model: recordModel?.chapterModel, toPage: (recordModel?.chapterModel?.pageCount.intValue ?? 1)-1)
                        READ_RECORD_CURRENT_CHAPTER_LOCATION = recordModel?.chapterModel?.getLocationFirst(page: (recordModel?.chapterModel?.pageCount.intValue ?? 1)-1).intValue ?? 0
                    }
                }else {
                    READ_RECORD_CURRENT_CHAPTER_LOCATION = cdModel?.location.intValue ?? 0
                }
            }
        }
        recordModel?.updateFont()
        updateRead(recordModel)
        chapterReadRequest()
        darkModeConfig(true)
    }
    
    /// 处理购买章节
    func handleBuyChapter(_ str: String) {
        let bookId = bookDetailModel?.bookId ?? ""
        let bookName = bookDetailModel?.name ?? ""
        let bookPrice = bookDetailModel?.price ?? 0
        let chapterName = readLockView.chapterModel?.chapterName ?? ""
        let chapterPrice = readLockView.chapterModel?.price ?? 0
        let chapterId = readLockView.chapterModel?.chapterId ?? NSNumber(value: -1)
        
        let pirce = bookDetailModel?.feeType == 1 ? bookPrice : chapterPrice
        if str == "解锁单章" {
            showSpringType(bookDetailModel?.feeType == 1 ? .chargedBook : .chargedOne, showStr1: bookDetailModel?.feeType == 1 ? bookName : chapterName, showStr2: "\(pirce)")
            WNSpringView.shared.isRightClosure = { [weak self] isRight in
                if isRight {
                    if WNSingleData.shared.userGold < pirce {
                        self?.wn_pushStoreVC()
                    }else {
                        self?.buyChapter(bookId, self?.bookDetailModel?.feeType == 1 ? -1 : chapterId, pirce)
                    }
                }
            }
        }else if str == "关闭页面" {
            readLockView.isHidden = true
            navView.titleName = recordModel?.chapterModel?.chapterName
        }else if str == "上一章" {
            handleChooseChapter(readLockView.chapterModel?.chapterPrevId ?? 0, false)
        }else if str == "下一章" {
            handleChooseChapter(readLockView.chapterModel?.chapterNextId ?? 0, false)
        }
    }
}

extension WNReadVC {
    
    func startReadTimer() {
        todayReadTime = activeTaskModel?.cost ?? 0
        stopReadTimer(true, false)
        readTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(readMonitor), userInfo: nil, repeats: true)
        RunLoop.current.add(readTimer!, forMode: .common)
    }
    
    @objc func readMonitor() {
        readTime += 1
        if let c = activeTaskModel?.children, c.count > 0 {
            if c.filter({$0.status == 1 }).count > 0 {
                for i in c {
                    if todayReadTime+readTime == i.accrueNum {
                        taskModel = i
                        activeShakeAnimation()
                        navView.ishiddRightBtn = false
                    }
                }
            }
        }
    }
    
    func stopReadTimer(_ needReport: Bool = true, _ needPop: Bool = true) {
        if readTimer != nil {
            readTimer?.invalidate()
            readTimer = nil
        }
        if needReport {
            readReportRequest(needPop)
        }
        readTime = 0
    }
    
    func readingPause(_ isPause: Bool = false) {
        if readTimer != nil {
            if isPause {
                readTimer?.fireDate = Date.distantFuture
            }else {
                readTimer?.fireDate = Date.init(timeIntervalSinceNow: 0)
            }
        }
    }
    
    func readReportRequest(_ needPop: Bool = true) {
        WNBuriedManager.shared.readReport(bookDetailModel?.bookId ?? "", time: readTime)
        if needPop {
            stopLimitedTimer()
            navView.isBegin = false
            navView.isPlay = false
            WNReadManager.shared.stopReading()
            audioAnimation()
            navigationController?.popViewController(animated: true)
        }
    }
    
    func activeShakeAnimation() {
        navView.rightBtn.layer.removeAllAnimations()
        let animation = CABasicAnimation.init(keyPath: "transform.scale")
        animation.duration = 0.8
        animation.fromValue = NSNumber(floatLiteral: 1)
        animation.toValue = NSNumber(floatLiteral: 1.2)
        animation.repeatCount = MAXFLOAT
        animation.autoreverses = true
        navView.rightBtn.layer.add(animation, forKey: nil)
    }
    
    func limitedAnimation() {
        rechargeBtn.layer.removeAllAnimations()
        if limitedModel != nil {
            let animation = CABasicAnimation.init(keyPath: "transform.scale")
            animation.duration = 0.8
            animation.fromValue = NSNumber(floatLiteral: 1)
            animation.toValue = NSNumber(floatLiteral: 1.2)
            animation.repeatCount = MAXFLOAT
            animation.autoreverses = true
            rechargeBtn.layer.add(animation, forKey: nil)
        }
    }
    
    func handleLimitedArr() {
        if limitedArr.count == 0 {
            limitedModel = nil
        }else {
            if limitedArr.count == 1 {
                limitedModel = limitedArr[0].expireTime == 0 ? nil : limitedArr[0]
            }else {
                let exArr = limitedArr.filter({$0.expireTime != 0})
                if exArr.count == 0 {
                    limitedModel = nil
                }else if exArr.count == 1 {
                    limitedModel = exArr.first
                }else {
                    limitedModel = exArr.sorted(by: {$0.gold > $1.gold}).first
                }
            }
        }
    }
    
    func startLimitedTimer() {
        stopLimitedTimer()
        limitedTime = limitedModel?.expireTime ?? 0
        if limitedTime != 0 {
            limitedTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(limitedMonitor), userInfo: nil, repeats: true)
            RunLoop.current.add(limitedTimer!, forMode: .common)
        }
    }
    
    @objc func limitedMonitor() {
        limitedTime -= 1
        if WNSpringView.shared.limitedModel != nil {
            WNSpringView.shared.limitedView.timeLabel.text = "\(limitedTime)".wn_toDuration() + " "
        }
        if limitedTime <= 0 {
            if WNSpringView.shared.limitedModel != nil {
                WNSpringView.shared.limitedView.timeLabel.text = ""
                hidenSpringView()
            }
            stopLimitedTimer()
            getLimitedRequest()
        }
    }
    
    func stopLimitedTimer() {
        if limitedTimer != nil {
            limitedTimer?.invalidate()
            limitedTimer = nil
        }
        limitedTime = 0
    }
    
    func audioAnimation() {
        if navView.isBegin {
            if navView.isPlay {
                navView.audioBtn.wn_pauseRotation(false)
            }else {
                navView.audioBtn.wn_pauseRotation(true)
            }
        }else {
            navView.audioBtn.wn_stopRotation()
        }
    }
}
